package com.google.code.sms.android.parser;

import java.io.Reader;
import java.util.List;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;

import com.google.code.sms.android.domain.IndexElement;
import com.google.code.sms.android.domain.Indexes;
import com.google.code.sms.android.util.ProgressListener;

import android.content.Context;
import com.google.code.sms.android.R;
import android.util.Log;

/**
 * @author Sindre Mehus
 */
public class IndexesParser extends AbstractParser {
    private static final String TAG = IndexesParser.class.getSimpleName();

    public IndexesParser(Context context) {
        super(context);
    }

    public Indexes parse(Reader reader, ProgressListener progressListener) throws Exception {

        long t0 = System.currentTimeMillis();
        updateProgress(progressListener, R.string.parser_reading);
        init(reader);

        List<IndexElement> elements = new ArrayList<IndexElement>();
        int eventType;
        String index = "#";
        boolean changed = false;

        do {
            eventType = nextParseEvent();
            if (eventType == XmlPullParser.START_TAG) {
                String name = getElementName();
                if ("indexes".equals(name)) {
                    changed = true;
                } else if ("index".equals(name)) {
                    index = get("name");
                } else if ("element".equals(name)) {
                    IndexElement element = new IndexElement();
                    element.setName(get("name"));
                    element.setId(get("id"));
                    element.setIndex(index);
                    elements.add(element);

                    if (elements.size() % 10 == 0) {
                        String msg = getContext().getResources().getString(R.string.parser_artist_count, elements.size());
                        updateProgress(progressListener, msg);
                    }
                } else if ("error".equals(name)) {
                    handleError();
                }
            }
        } while (eventType != XmlPullParser.END_DOCUMENT);

        validate();

        if (!changed) {
            return null;
        }

        long t1 = System.currentTimeMillis();
        Log.d(TAG, "Got " + elements.size() + " artist(s) in " + (t1 - t0) + "ms.");

        String msg = getContext().getResources().getString(R.string.parser_artist_count, elements.size());
        updateProgress(progressListener, msg);

        return new Indexes(elements);
    }
}